package com.hqq.concurrency.semaphone;

/**
 * FruitShop
 * Created by heqianqian on 2017/7/30.
 */
public class FruitShop {

    private FruitBowl[] fruitBowls = {
            new FruitBowl(),
            new FruitBowl(),
            new FruitBowl()
    };

    private boolean[] available = {
            true,
            true,
            true
    };

    private Semaphore semaphore;

    public FruitShop() {
        for (int i = 0; i < 100; i++) {
            fruitBowls[0].put(new Fruit(FruitType.APPLE));
            fruitBowls[0].put(new Fruit(FruitType.BANANA));
            fruitBowls[0].put(new Fruit(FruitType.ORANGE));
        }
        semaphore = new Semaphore(3);
    }

    public synchronized int countFruit() {
        return fruitBowls[0].countFruit() + fruitBowls[1].countFruit()
                + fruitBowls[2].countFruit();
    }

    public synchronized FruitBowl takeBowl() {
        FruitBowl fruitBowl = null;

        try {
            semaphore.acquire();
            if (available[0]) {
                fruitBowl = fruitBowls[0];
                available[0] = false;
            } else if (available[1]) {
                fruitBowl = fruitBowls[1];
                available[1] = false;
            } else if (available[2]) {
                fruitBowl = fruitBowls[2];
                available[2] = false;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
        return fruitBowl;
    }

    public synchronized void returnBowl(FruitBowl fruitBowl) {
        if (fruitBowl == fruitBowls[0]) {
            available[0] = true;
        } else if (fruitBowl == fruitBowls[1]) {
            available[1] = true;
        } else if (fruitBowl == fruitBowls[2]) {
            available[2] = true;
        }
    }

}
